using MaterialSkin.Controls;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace VideoAutoGenerator.UI.UserControls
{
    public partial class WorkManagementControl : MaterialCard
    {
        private MaterialLabel titleLabel;
        private MaterialListView workListView;
        private MaterialButton refreshButton;
        private MaterialButton previewButton;
        private MaterialButton deleteButton;
        private MaterialButton openFolderButton;
        private MaterialButton renameButton;
        private string videoOutputDirectory;
        private WorkPreviewControl previewControl;

        public WorkManagementControl()
        {
            InitializeComponent();
            LoadVideoOutputDirectory();
            LoadWorks();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // 创建控件
            CreateControls();

            // 设置布局
            SetupLayout();

            // 添加事件处理程序
            SetupEventHandlers();

            this.ResumeLayout(false);
        }

        private void CreateControls()
        {
            titleLabel = new MaterialLabel();
            workListView = new MaterialListView();
            refreshButton = new MaterialButton();
            previewButton = new MaterialButton();
            deleteButton = new MaterialButton();
            openFolderButton = new MaterialButton();
            renameButton = new MaterialButton();
        }

        private void SetupLayout()
        {
            // 设置控件属性
            this.AutoScroll = true;
            this.Dock = DockStyle.Fill;
            this.Padding = new Padding(20);

            // 标题
            titleLabel.Text = "作品管理";
            titleLabel.AutoSize = true;
            titleLabel.Font = new Font(titleLabel.Font.FontFamily, 16, FontStyle.Bold);
            titleLabel.Location = new Point(10, 10);

            // 作品列表
            workListView.Width = 700;
            workListView.Height = 400;
            workListView.Location = new Point(10, 50);
            workListView.View = View.Details;
            workListView.FullRowSelect = true;
            workListView.GridLines = true;
            workListView.MultiSelect = false;

            // 添加列
            workListView.Columns.Add("文件名", 200);
            workListView.Columns.Add("创建时间", 150);
            workListView.Columns.Add("文件大小", 100);
            workListView.Columns.Add("时长", 100);
            workListView.Columns.Add("分辨率", 150);

            // 按钮
            refreshButton.Text = "刷新";
            refreshButton.Width = 80;
            refreshButton.Location = new Point(10, 460);

            previewButton.Text = "预览";
            previewButton.Width = 80;
            previewButton.Location = new Point(100, 460);

            deleteButton.Text = "删除";
            deleteButton.Width = 80;
            deleteButton.Location = new Point(190, 460);

            openFolderButton.Text = "打开目录";
            openFolderButton.Width = 100;
            openFolderButton.Location = new Point(280, 460);

            renameButton.Text = "重命名";
            renameButton.Width = 80;
            renameButton.Location = new Point(390, 460);

            // 添加控件到面板
            this.Controls.Add(titleLabel);
            this.Controls.Add(workListView);
            this.Controls.Add(refreshButton);
            this.Controls.Add(previewButton);
            this.Controls.Add(deleteButton);
            this.Controls.Add(openFolderButton);
            this.Controls.Add(renameButton);
        }

        private void SetupEventHandlers()
        {
            refreshButton.Click += RefreshButton_Click;
            previewButton.Click += PreviewButton_Click;
            deleteButton.Click += DeleteButton_Click;
            openFolderButton.Click += OpenFolderButton_Click;
            renameButton.Click += RenameButton_Click;
            workListView.DoubleClick += WorkListView_DoubleClick;
        }

        private void LoadVideoOutputDirectory()
        {
            // 从配置中获取视频输出目录
            videoOutputDirectory = Core.ConfigManager.Instance.GetString("outputDirVideo", "./output/videos");
            
            // 获取配置文件所在的目录
            string configDirectory = Path.GetDirectoryName(Core.ConfigManager.Instance.ConfigPath);
            
            // 如果是相对路径，转换为相对于配置文件的绝对路径
            if (!Path.IsPathRooted(videoOutputDirectory))
            {
                videoOutputDirectory = Path.GetFullPath(Path.Combine(configDirectory, videoOutputDirectory));
            }
        }

        private void LoadWorks()
        {
            workListView.Items.Clear();

            try
            {
                if (Directory.Exists(videoOutputDirectory))
                {
                    string[] videoFiles = Directory.GetFiles(videoOutputDirectory, "*.mp4");
                    
                    foreach (string videoFile in videoFiles)
                    {
                        FileInfo fileInfo = new FileInfo(videoFile);
                        
                        var item = new ListViewItem(fileInfo.Name);
                        item.SubItems.Add(fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm"));
                        item.SubItems.Add(GetFileSize(fileInfo.Length));
                        item.SubItems.Add("未知"); // 时长需要通过FFmpeg获取
                        item.SubItems.Add("未知"); // 分辨率需要通过FFmpeg获取
                        item.Tag = videoFile; // 保存完整路径
                        
                        workListView.Items.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载作品列表时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetFileSize(long size)
        {
            if (size < 1024)
                return $"{size} B";
            else if (size < 1024 * 1024)
                return $"{size / 1024.0:F2} KB";
            else if (size < 1024 * 1024 * 1024)
                return $"{size / (1024.0 * 1024.0):F2} MB";
            else
                return $"{size / (1024.0 * 1024.0 * 1024.0):F2} GB";
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            LoadWorks();
        }

        private void PreviewButton_Click(object sender, EventArgs e)
        {
            if (workListView.SelectedItems.Count > 0)
            {
                string videoPath = workListView.SelectedItems[0].Tag.ToString();
                PreviewVideo(videoPath);
            }
            else
            {
                MessageBox.Show("请选择要预览的作品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void WorkListView_DoubleClick(object sender, EventArgs e)
        {
            PreviewButton_Click(sender, e);
        }

        private void PreviewVideo(string videoPath)
        {
            // 创建预览对话框
            Form previewForm = new Form();
            previewForm.Text = "作品预览";
            previewForm.Size = new Size(800, 600);
            previewForm.StartPosition = FormStartPosition.CenterParent;
            previewForm.Icon = this.FindForm()?.Icon;

            // 创建预览控件
            previewControl = new WorkPreviewControl();
            previewControl.Dock = DockStyle.Fill;
            
            // 加载视频
            previewControl.LoadVideo(videoPath);
            
            previewForm.Controls.Add(previewControl);
            previewForm.ShowDialog(this.FindForm());
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            if (workListView.SelectedItems.Count > 0)
            {
                string fileName = workListView.SelectedItems[0].Text;
                string videoPath = workListView.SelectedItems[0].Tag.ToString();
                
                DialogResult result = MessageBox.Show($"确定要删除作品 '{fileName}' 吗？\n\n注意：此操作不可撤销！", 
                    "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result == DialogResult.Yes)
                {
                    try
                    {
                        File.Delete(videoPath);
                        LoadWorks(); // 刷新列表
                        MessageBox.Show("作品已删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"删除作品时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择要删除的作品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void OpenFolderButton_Click(object sender, EventArgs e)
        {
            if (workListView.SelectedItems.Count > 0)
            {
                string videoPath = workListView.SelectedItems[0].Tag.ToString();
                
                try
                {
                    // 打开文件所在的目录并选中文件
                    Process.Start("explorer.exe", $"/select,\"{videoPath}\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"打开目录时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                // 如果没有选中文件，则打开视频输出目录
                try
                {
                    if (Directory.Exists(videoOutputDirectory))
                    {
                        Process.Start("explorer.exe", $"\"{videoOutputDirectory}\"");
                    }
                    else
                    {
                        MessageBox.Show("视频输出目录不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"打开目录时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void RenameButton_Click(object sender, EventArgs e)
        {
            if (workListView.SelectedItems.Count > 0)
            {
                var selectedItem = workListView.SelectedItems[0];
                string oldFileName = selectedItem.Text;
                string videoPath = selectedItem.Tag.ToString();
                string directory = Path.GetDirectoryName(videoPath);
                
                // 弹出重命名对话框
                Form renameForm = new Form();
                renameForm.Text = "重命名作品";
                renameForm.Size = new Size(400, 150);
                renameForm.StartPosition = FormStartPosition.CenterParent;
                renameForm.FormBorderStyle = FormBorderStyle.FixedDialog;
                renameForm.MaximizeBox = false;
                renameForm.MinimizeBox = false;
                renameForm.Icon = this.FindForm()?.Icon;
                
                MaterialLabel label = new MaterialLabel();
                label.Text = "请输入新文件名:";
                label.Location = new Point(20, 20);
                label.AutoSize = true;
                
                MaterialTextBox textBox = new MaterialTextBox();
                textBox.Text = Path.GetFileNameWithoutExtension(oldFileName);
                textBox.Location = new Point(20, 50);
                textBox.Width = 350;
                
                MaterialButton okButton = new MaterialButton();
                okButton.Text = "确定";
                okButton.Location = new Point(100, 80);
                
                MaterialButton cancelButton = new MaterialButton();
                cancelButton.Text = "取消";
                cancelButton.Location = new Point(200, 80);
                
                okButton.Click += (s, ev) => {
                    if (!string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        try
                        {
                            string newFileName = textBox.Text + Path.GetExtension(oldFileName);
                            string newFilePath = Path.Combine(directory, newFileName);
                            
                            if (File.Exists(newFilePath) && !newFilePath.Equals(videoPath, StringComparison.OrdinalIgnoreCase))
                            {
                                MessageBox.Show("目标文件名已存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }
                            
                            File.Move(videoPath, newFilePath);
                            renameForm.Close();
                            LoadWorks(); // 刷新列表
                            MessageBox.Show("作品已重命名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"重命名作品时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                };
                
                cancelButton.Click += (s, ev) => {
                    renameForm.Close();
                };
                
                renameForm.Controls.Add(label);
                renameForm.Controls.Add(textBox);
                renameForm.Controls.Add(okButton);
                renameForm.Controls.Add(cancelButton);
                
                renameForm.ShowDialog(this.FindForm());
            }
            else
            {
                MessageBox.Show("请选择要重命名的作品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }
}